﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using HMS.Data;
using HMS.ClassLibrary;
using System.Threading;

namespace HMS
{
    /// <summary>
    /// Interaction logic for ScanWindow.xaml
    /// </summary>
    public partial class ScanWindow : Window
    {
        private HMSEntities HMSContext;
        private ProgressWindow ProgressWindow;
        FormAction FormAction;

        public ScanWindow()
        {
            InitializeComponent();
            HMSContext = new HMSEntities();
            InitializeControlState();
            CurrentFormAction = FormAction.View;
        }
        //triggesr updateControlState() when form action changes
        public FormAction CurrentFormAction
        {
            set
            {
                FormAction = value;
                UpdateContolState();
            }
            get { return FormAction; }

        }

        private void InitializeControlState()
        {
            //set the autocomplete text box data source
           // ScanSubCategoryAutocompleteTextBox.ItemsSource = HMSContext.ReportTypes.Where(r => r.ReportSubCategory.ReportMainCategory.ServiceTypeID == 1);
            ScanMainCategoryAutocompleteTextBox.ItemsSource = HMSContext.ReportMainCategories.Where(r=> r.ServiceTypeID==1);

            //set payment methods
            PaymentMethodComboBox.DataContext = HMSContext.PaymentMethods;

            //set  Calendar dates to today
            AppointmentDatePicker.SelectedDate = DateTime.Now;
            CollectionDatePicker.SelectedDate = DateTime.Now;

            //set payment method to default 'cash'
            PaymentMethodComboBox.SelectedValue = 1;

            //set x-ray list
            ReferenceAutocompleteTextBox.ItemsSource = HMSContext.Reportings.Where(r => r.ReportType.ReportSubCategory.ReportMainCategory.ServiceTypeID == 1);

        }

        private void ResetControlValues()
        {
            //reset channeling details
            ScanMainCategoryAutocompleteTextBox.SelectedItem = null;
            ScanSubCategoryAutocompleteTextBox.SelectedItem = null;
            ScanTypeAutocompleteTextBox.SelectedItem = null;
            AppointmentDatePicker.SelectedDate = DateTime.Now;
            CollectionDatePicker.SelectedDate = DateTime.Now;

            //reset patient details
            PatientNameTextBox.Text = "";
            PatientContactNoTextBox.Text = "";

            //reset summary 
            DoctorFeeTextBlock.Text = "0.00";
            HospitalFeeTextBlock.Text = "0.00";
            UrgentFeeTextBlock.Text = "0.00";
            TotalReceiptAmountTextBlock.Text = "0.00";
        }

        private decimal CalculateTotalReceiptAmount(ReportType reportType, decimal discountPercentage = 0, decimal taxPercentage = 0)
        {
            try
            {
                decimal netTotal = (decimal)(reportType.DoctorFee + reportType.HospitalFee);
                decimal totalDiscount = this.CalculateTotalDiscountAmount(reportType, discountPercentage);
                return netTotal + this.CalculateTotalTaxAmount(reportType, discountPercentage, taxPercentage);

            }
            catch (Exception)
            {

                throw;
            }

        }
        private decimal CalculateTotalTaxAmount(ReportType reportType, decimal discountPercentage = 0, decimal taxPercentage = 0)
        {
            try
            {
                decimal netTotal = (decimal)(reportType.DoctorFee + reportType.HospitalFee);
                decimal totalDiscount = (netTotal * discountPercentage) / 100;
                return ((netTotal - totalDiscount) * taxPercentage) / 100;

            }
            catch (Exception)
            {

                throw;
            }

        }
        private decimal CalculateTotalDiscountAmount(ReportType reportType, decimal discountPercentage = 0)
        {
            try
            {
                decimal netTotal = (decimal)(reportType.DoctorFee + reportType.HospitalFee);
                return (netTotal * discountPercentage) / 100;

            }
            catch (Exception)
            {

                throw;
            }

        }

        private bool ValidateControlValues()
        {

            if (ScanMainCategoryAutocompleteTextBox.SelectedItem == null)
            {
                MessageBox.Show(Properties.Resources.ScanMainCategoryNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (ScanSubCategoryAutocompleteTextBox.SelectedItem == null)
            {
                MessageBox.Show(Properties.Resources.ScanSubCategoryNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }

            if (ScanTypeAutocompleteTextBox.SelectedItem == null)
            {
                MessageBox.Show(Properties.Resources.DoctorTypeNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (AppointmentDatePicker.SelectedDate == null)
            {
                MessageBox.Show(Properties.Resources.AppoinmentDateNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;

            }
            if (CollectionDatePicker.SelectedDate == null)
            {
                MessageBox.Show(Properties.Resources.CollectiontDateNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;

            }
            if (String.IsNullOrEmpty(PatientNameTextBox.Text.Trim()))
            {
                MessageBox.Show(Properties.Resources.PatientNameNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
            if (PatientContactNoTextBox.Text.Contains("_"))
            {
                MessageBox.Show(Properties.Resources.ContactNumberInvalid, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }

            return true;
        }
        private void DisplayDetails(HMS.Data.Reporting reporting)
        {
            try
            {
                //display channeling details
                ReferenceAutocompleteTextBox.SelectedItem = reporting;
                ScanMainCategoryAutocompleteTextBox.SelectedItem = reporting.ReportType.ReportSubCategory.ReportMainCategory;
                ScanSubCategoryAutocompleteTextBox.SelectedItem = reporting.ReportType.ReportSubCategory;
                ScanTypeAutocompleteTextBox.SelectedItem = reporting.ReportType;
                AppointmentDatePicker.SelectedDate = reporting.AppointmentDateTime;
                CollectionDatePicker.SelectedDate = reporting.CollectionDateTime;

                //display patient details
                PatientNameTextBox.Text = reporting.Patient.Name;
                PatientContactNoTextBox.Text = reporting.Patient.ContactNumber;

                //display summary details
                HospitalFeeTextBlock.Text = reporting.Receipt.HospitalFee.ToString();
                DoctorFeeTextBlock.Text = reporting.Receipt.DoctorFee.ToString();
                UrgentFeeTextBlock.Text = reporting.Receipt.UrgentFee.ToString();
                TotalReceiptAmountTextBlock.Text = reporting.Receipt.TotalAmount.ToString();
            }
            catch (Exception)
            {

                throw;
            }

        }

        private void UpdateContolState()
        {
            switch (this.CurrentFormAction)
            {
                case FormAction.View:
                    ReferenceAutocompleteTextBox.ItemsSource = HMSContext.Reportings.Where(r => r.ReportType.ReportSubCategory.ReportMainCategory.ServiceTypeID == 1);
                    ReferenceAutocompleteTextBox.IsEnabled = true;

                    ScanMainCategoryAutocompleteTextBox.ItemsSource = null;
                    ScanMainCategoryAutocompleteTextBox.Text = "";

                    ScanTypeAutocompleteTextBox.ItemsSource = null;
                    ScanTypeAutocompleteTextBox.Text = "";

                    ScanSubCategoryAutocompleteTextBox.ItemsSource = null;
                    ScanSubCategoryAutocompleteTextBox.Text = "";


                    //set button states
                    SaveButton.IsEnabled = false;
                    RefreshSummaryButton.IsEnabled = false;
                    NewButton.IsEnabled = true;
                    PrintButton.IsEnabled = true;
                    CancelButton.IsEnabled = true;
                    break;


                case FormAction.New:
                    ResetControlValues();
                    InitializeControlState();

                    ReferenceAutocompleteTextBox.ItemsSource = null;
                    ReferenceAutocompleteTextBox.IsEnabled = false;

                    //set button states
                    SaveButton.IsEnabled = true;
                    RefreshSummaryButton.IsEnabled = true;
                    NewButton.IsEnabled = false;
                    PrintButton.IsEnabled = false;
                    CancelButton.IsEnabled = true;
                    break;
            }

        }
        private void Save()
        {
            try
            {
                if (ValidateControlValues())
                {

                    //reporting details
                    DateTime? appoinmentDate = AppointmentDatePicker.SelectedDate;
                    DateTime? collectionDate = CollectionDatePicker.SelectedDate;
                    String reference = HMSContext.NextSystemNumber(3).First();
                    ReportType reportType = ScanTypeAutocompleteTextBox.SelectedItem as ReportType;
                    Boolean? isUrgent = IsUrgentCheckBox.IsChecked;

                    //patient details
                    string patientName = PatientNameTextBox.Text;
                    string patientContactNo = PatientContactNoTextBox.Text;

                    //payment details
                    PaymentMethod paymentMethod = PaymentMethodComboBox.SelectedItem as PaymentMethod;
                    DateTime receiptDateTime = DateTime.Now;
                    decimal? totalAmount = 0;
                    decimal? urgentFee = 0;
                    if (isUrgent == true)
                    {
                        decimal taxPercentage = (decimal)HMSContext.Taxes.Where(t => t.TaxID == 2).First().Percentage;
                        urgentFee = this.CalculateTotalTaxAmount(reportType, 0, taxPercentage);
                        totalAmount = this.CalculateTotalReceiptAmount(reportType, 0, taxPercentage);
                    }
                    else
                    {
                        urgentFee = 0;
                        totalAmount = this.CalculateTotalReceiptAmount(reportType, 0, 0);
                    }


                    Patient patient = new Patient();
                    patient.Name = patientName;
                    patient.ContactNumber = patientContactNo;

                    Receipt receipt = new Receipt();
                    receipt.ServiceTypeID = 1;
                    receipt.PaymentMethodID = paymentMethod.PaymentMethodID;
                    receipt.ReceiptDateTime = receiptDateTime;
                    receipt.DoctorFee = reportType.DoctorFee;
                    receipt.HospitalFee = reportType.HospitalFee;
                    receipt.DiscountAmount = 0;
                    receipt.UrgentFee = urgentFee;
                    receipt.TotalAmount = totalAmount;
                    receipt.Reference = reference;

                    Reporting reporting = new Reporting();
                    reporting.ReportType = reportType;
                    reporting.Receipt = receipt;
                    reporting.Patient = patient;
                    reporting.Reference = reference;
                    reporting.CollectionDateTime = collectionDate;
                    reporting.AppointmentDateTime = appoinmentDate;
                    reporting.IsUrgent = isUrgent;
                    reporting.UserID = HMSApplication.Session.User.UserID;

                    HMSContext.AddToReportings(reporting);
                    int? affectedRowCount = HMSContext.SaveChanges();
                    if (affectedRowCount != null && affectedRowCount > 0)
                    {
                        ResetControlValues();
                        if (PrintReceiptCheckBox.IsChecked == true)
                        {
                            this.Print(reporting);
                        }

                        //set the form action to view mode and display the saved channeling details
                        this.CurrentFormAction = FormAction.View;
                        this.DisplayDetails(reporting);
                        MessageBox.Show(Properties.Resources.SaveSuccessful, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Information);

                    }
                    else
                    {
                        MessageBox.Show(Properties.Resources.UnknownError, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }

            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }
        private void UpdateSummary()
        {
            try
            {
                if (CurrentFormAction == FormAction.New)
                {
                    bool isUrgent = IsUrgentCheckBox.IsChecked.Value;
                    ReportType reportType = ScanTypeAutocompleteTextBox.SelectedItem as ReportType;
                    if (isUrgent == true)
                    {
                        decimal taxPercentage = (decimal)HMSContext.Taxes.Where(t => t.TaxID == 2).First().Percentage;
                        HospitalFeeTextBlock.Text = reportType.HospitalFee.Value.ToString();
                        DoctorFeeTextBlock.Text = reportType.DoctorFee.Value.ToString();
                        UrgentFeeTextBlock.Text = this.CalculateTotalTaxAmount(reportType, 0, taxPercentage).ToString();
                        TotalReceiptAmountTextBlock.Text = this.CalculateTotalReceiptAmount(reportType, 0, taxPercentage).ToString();
                    }
                    else
                    {
                        HospitalFeeTextBlock.Text = reportType.HospitalFee.Value.ToString();
                        DoctorFeeTextBlock.Text = reportType.DoctorFee.Value.ToString();
                        UrgentFeeTextBlock.Text = "0.00";
                        TotalReceiptAmountTextBlock.Text = this.CalculateTotalReceiptAmount(reportType, 0, 0).ToString();
                    }
                }

            }
            catch (Exception)
            {

                throw;

            }

        }

        private void Print(HMS.Data.Reporting reporting)
        {
            try
            {
                Printer printer = new Printer();
                printer.Print(reporting.Receipt, ReceiptReportType.ScanReceiptDoctorReport);
                printer.Print(reporting.Receipt, ReceiptReportType.ScanReceiptHospitalReport);
            }
            catch (Exception)
            {

                throw;
            }

        }
        //bacground worker used to show progrees dialog
        private void PrintBackgroundWorker(object sender, DoWorkEventArgs e)
        {
            try
            {
                //dispathcher needs to access ui control without having exceptions
                this.Dispatcher.Invoke((Action)(() =>
                {
                    Reporting selectedReporting = ReferenceAutocompleteTextBox.SelectedItem as Reporting;
                    this.Print(selectedReporting);
                }));

            }
            catch (Exception)
            {
                throw;
            }
        }
        private void SaveBackgroundWorker(object sender, DoWorkEventArgs e)
        {
            try
            {
                //dispathcher needs to access ui control without having exceptions
                this.Dispatcher.Invoke((Action)(() =>
                {
                    this.Save();
                }));

            }
            catch (Exception)
            {
                throw;
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //show the busy indicator of saving
                ProgressWindow = new ProgressWindow(this.SaveBackgroundWorker);
                ProgressWindow.Owner = this;
                ProgressWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.CurrentFormAction = FormAction.New;

                //Context refreshed to get new reference
                HMSContext.Refresh(System.Data.Objects.RefreshMode.StoreWins, HMSContext.SystemNumbers);
                SystemNumber nextSystemNumber = HMSContext.SystemNumbers.Where(s => s.SystemNumberID == 3).First();
                ReferenceAutocompleteTextBox.Text = nextSystemNumber.Prefix + nextSystemNumber.NextNumber;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void ReferenceAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ReferenceAutocompleteTextBox.SelectedItem != null)
                {
                    Reporting selectedReporting = ReferenceAutocompleteTextBox.SelectedItem as Reporting;
                    this.DisplayDetails(selectedReporting);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

      
        private void IsUrgentCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ScanTypeAutocompleteTextBox.SelectedItem != null)
                {
                    this.UpdateSummary();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }

        private void IsUrgentCheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ScanTypeAutocompleteTextBox.SelectedItem != null)
                {
                    this.UpdateSummary();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }

        private void ScanMainCategoryAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
               
                if (CurrentFormAction==FormAction.New && ScanMainCategoryAutocompleteTextBox.SelectedItem != null)
                {
                    ReportMainCategory selectedMainCategory=ScanMainCategoryAutocompleteTextBox.SelectedItem as  ReportMainCategory;
                    ScanSubCategoryAutocompleteTextBox.ItemsSource = HMSContext.ReportSubCategories.Where(r => r.ReportMainCategoryID == selectedMainCategory.ReportMainCategoryID);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }

        private void ScanSubCategoryAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (CurrentFormAction == FormAction.New && ScanMainCategoryAutocompleteTextBox.SelectedItem != null && ScanSubCategoryAutocompleteTextBox.SelectedItem != null)
                {
                    ReportSubCategory selectedSubCategory = ScanSubCategoryAutocompleteTextBox.SelectedItem as ReportSubCategory;
                    ScanTypeAutocompleteTextBox.ItemsSource = HMSContext.ReportTypes.Where(r => r.ReportSubCategoryID == selectedSubCategory.ReportSubCategoryID);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }

        private void ScanTypeAutocompleteTextBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (ScanTypeAutocompleteTextBox.SelectedItem != null)
                {
                    this.UpdateSummary();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);

            }
        }

        private void PrintButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ReferenceAutocompleteTextBox.SelectedItem != null)
                {
                    //show the busy indicator of saving
                    ProgressWindow = new ProgressWindow(this.PrintBackgroundWorker);
                    ProgressWindow.Owner = this;
                    ProgressWindow.ShowDialog();
                }
                else
                {
                    MessageBox.Show(Properties.Resources.ChannelingNotSet, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Properties.Resources.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }
    }
}
